package com.rm.zeyou.service.impl;

import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rm.zeyou.constant.CommonConstants;
import com.rm.zeyou.constant.NumberConstants;
import com.rm.zeyou.entity.Recruitment;
import com.rm.zeyou.exception.ErrorCodeException;
import com.rm.zeyou.exception.ErrorCodeExceptionEnum;
import com.rm.zeyou.mapper.RecruitmentMapper;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.RecruitmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.service.UserService;
import com.rm.zeyou.vo.request.ApplyRecruitmentVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 技师入住表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-12 15:55:08
 */
@Service
public class RecruitmentServiceImpl extends ServiceImpl<RecruitmentMapper, Recruitment> implements RecruitmentService {
    @Resource
    private RecruitmentMapper recruitmentMapper;
    @Resource
    private UserService userService;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> applyRecruitment(Long userId, ApplyRecruitmentVo applyVo) {
        //先查询该用户是否有正在审核或者审核成功的申请
        int applyCount = recruitmentMapper.selectCount(new LambdaQueryWrapper<Recruitment>()
                .eq(Recruitment::getUserId, userId)
                .in(Recruitment::getAuditStatus, NumberConstants.ZERO_CONSTANTS, NumberConstants.ONE_CONSTANTS)).intValue();
        if (applyCount>0){
            throw new ErrorCodeException(ErrorCodeExceptionEnum.AUDITING);
        }
        userService.checkCode(applyVo.getRecruitmentTel(),applyVo.getCode(), CommonConstants.APPLY_RECRUITMENT);

        Recruitment insertRecruitment = new Recruitment();
        insertRecruitment.setUserId(userId);
        insertRecruitment.setWorkCity(applyVo.getWorkCity());
        insertRecruitment.setRecruitmentName(applyVo.getRecruitmentName());
        insertRecruitment.setRecruitmentSex(applyVo.getRecruitmentSex());
        insertRecruitment.setRecruitmentAge(IdcardUtil.getAgeByIdCard(applyVo.getRecruitmentRealNum()));
        insertRecruitment.setRecruitmentTel(applyVo.getRecruitmentTel());
        insertRecruitment.setReceivingArea(applyVo.getReceivingArea());
        insertRecruitment.setRecruitmentRealNum(applyVo.getRecruitmentRealNum());
        insertRecruitment.setWorkExperience(applyVo.getWorkExperience());
        insertRecruitment.setFrontPhoto(applyVo.getFrontPhoto());
        insertRecruitment.setIdCardPhoto(applyVo.getIdCardPhoto());

        return ApiRestResponse.success(recruitmentMapper.insert(insertRecruitment));
    }
}
